class Solution
{
public:
    long long maximumTotalDamage(vector<int> &power)
    {
        long long result = 0;
        map<int, int> m;
        for (auto p : power)
        {
            ++m[p];
        }
        vector<long long> v, c;
        for (auto &[p, count] : m)
        {
            v.push_back(p);
            c.push_back(count);
        }
        int n = v.size();
        vector<long long> dp(n, 0);

        for (int i = 0; i < n; ++i)
        {
            dp[i] = v[i] * c[i];
            if (i >= 1 && v[i] > v[i - 1] + 2)
            {
                dp[i] = max(result, dp[i]);
                dp[i] = max(dp[i], dp[i - 1] + v[i] * c[i]);
            }
            else if (i >= 2 && v[i] > v[i - 2] + 2)
            {
                dp[i] = max(dp[i], dp[i - 2] + v[i] * c[i]);
            }
            else if (i >= 3)
            {
                dp[i] = max(dp[i], dp[i - 3] + v[i] * c[i]);
            }
            result = max(result, dp[i]);
            dp[i] = result;
        }
        return result;
    }
};